package app.services.bus.subscibe;

import app.Const;
import app.constant.OrderConstant;
import app.models.order.Order;
import app.services.OrderService;
import app.services.bus.event.WithdrawalsEvent;
import bank.BankConstant;
import bank.BankService;
import bank.resp.MerchantAccntRspDto;
import com.google.common.base.Optional;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import goja.Logger;
import goja.StringPool;
import org.joda.time.DateTime;

/**
 * <p> </p>
 *
 * @author sogYF
 * @version 1.0
 * @since JDK 1.6
 */
public class WithdrawalsSubscriber {


    public WithdrawalsSubscriber(EventBus eventBus) {
        eventBus.register(this);
    }


    @Subscribe
    public void hanleWithdrawals(WithdrawalsEvent withdrawalsEvent) {
        // 提现订单
        Order order = OrderService.me.buildOrder(0, 0, "融理平台", BankConstant.MERCHANT_PRODUCT_NO, StringPool.EMPTY, OrderConstant.WITHDRAWALS);
        order.set("trade_amount", withdrawalsEvent.amount);
        order.set("remark", withdrawalsEvent.desc);
        try {
            Optional<MerchantAccntRspDto> chargingAccnt = BankService.me.withdrawMerchantAccnt(DateTime.now(), order.getStr("trade_no"),
                    withdrawalsEvent.amount);
            if (chargingAccnt.isPresent()) {
                boolean ok = chargingAccnt.get().getOrderStatus() == OrderConstant.TRADE_SUCCESS;
                if (ok) {
                    order.set(Const.FIELD_STATUS, OrderConstant.TRADE_SUCCESS);
                } else {
                    order.set(Const.FIELD_STATUS, OrderConstant.TRADE_FAILURE);
                }
            }
        } catch (Exception e) {
            Logger.error("提现失败，错误信息{}", e.getMessage(), e);
            order.set(Const.FIELD_STATUS, OrderConstant.TRADE_FAILURE);
        } finally {
            order.save();
        }
    }

}
